<script setup>
import {getCurrentInstance, onBeforeMount , reactive, ref } from "vue";
const {proxy} = getCurrentInstance();
import {currentLogin, updateLoginById,searchFields} from "@/api/basal.js";
import {ResultEnums} from "@/enums/ResultStatusEnums.js";
import {useRouter} from "vue-router";
const router = useRouter();
const formRef = ref(null)
const errorMessage = ref(null)
const currentSystemCode = ref(import.meta.env.VITE_SYSTEM_CODE)
const form = reactive({ id:'',loginName:'',moduleName:'user',expands:{}});
import ExpandFields from '@/components/debris/ExpandFields.vue'
const fields = ref([])
onBeforeMount (() => {
  onLoad().then(data=>{
    Object.keys(data).forEach(key => {
      form[key] = data[key]
    })
    if(form.hasOwnProperty('expands')){
      const expands =  form['expands']
      form['expands'] = expands||{};
    }else {
      form['expands'] = {};
    }

    loadFields(currentSystemCode.value,form.moduleName,form.id).then(result => {
      fields.value = result
    })

  })
})

async function onLoad(){
  let result = await currentLogin(form.moduleName);
  return result.code === ResultEnums.SUCCESS? result.data: {}
}

async function loadFields(systemCode,moduleName,loginId){
  const result = await searchFields(systemCode,moduleName,{isEnable:true,loginId:loginId})
  return result.code === ResultEnums.SUCCESS? result.data : []
}

async function confirm(e){
  e.preventDefault();
  if (formRef.value.checkValidity()) {
    const result = await updateLoginById(form.id,form)
    if(result.code === ResultEnums.SUCCESS ){
      router.go(0);
    }else {
      errorMessage.value = result.message;
    }
  } else {
    formRef.value.reportValidity();
  }
}
</script>

<template>
  <div class="row g-4 settings-section">
    <div class="app-card app-card-settings shadow-sm p-4">
      <div class="app-card-body">
        <form class="settings-form" ref="formRef">
          <div class="mb-3">
            <label for="setting-input-1" class="form-label">账号名称</label>
            <input type="text" class="form-control" disabled="disabled" v-model="form.loginName" required>
          </div>
          <ExpandFields v-if="fields" :fieldItems="fields" v-model="form.expands"/>
          <Transition v-if="errorMessage">
            <div class="alert alert-warning alert-dismissible fade" :class="errorMessage&&' show '" role="alert">
              <strong>错误提示!</strong> {{ errorMessage }}
              <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
          </Transition>
          <button type="submit" class="btn app-btn-primary" @click="confirm">确认</button>
        </form>
      </div><!--//app-card-body-->

    </div><!--//app-card-->
  </div><!--//row-->
</template>

<style scoped>
:deep(.el-date-editor) {
  height: 2.5rem;
  width: 100%;
}
:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 0 var(--el-input-border-color,var(--el-border-color)) inset;
}
</style>